<?php
class controller_admin_index extends system_user_controller_panel {
	
	private $_namespace = 'CMSDREAM';
	public function init() {
		parent::init();
		$this->layout()->setLayout('panelLayout');
	}
	
	public function action_index() {
		if($this->admin()) {
			return;
		}
		$this->render();
	}
	
	public function action_selectLanguage() {
		if(!($lang = $this->_post('language'))) {
			$this->_go($this->_post('referer'));
		}
		system_user_instance::getInstance()->getSession()->setLanguage($lang);
		if($this->user) {
			$this->user->setLang($lang);
			$this->user->update();
		}
		$this->_go($this->_post('referer'));
	}
	
	public function action_login() {
		$this->view->request = $this->getRequest();
		$this->view->error = array();
		if($this->getRequest()->isPost()) {
			$this->referer = trim($this->_post('referer'));
			try {
				if(!system_image_captcha::auth($this->_post('validCode'), $this->_namespace)) {
					$this->view->error['validCode'] = 'Valid code is not matched.';
				}
				
				$account = trim($this->_post('account'));
				$password = trim($this->_post('password'));
				$concept = new system_user_concept();
				if(!($row = $concept->fetch(array('identity = ?' => $account)))) {
					$this->view->error['auth'] = 'Authenticate failed2.';
				}
				if($row && !$row->auth($password)) {
					$this->view->error['auth'] = 'Authenticate failed1.';
				}
				
				if(count($this->view->error) == 0) {
					$secure = system_user_instance::getInstance()
							->getSession()
							->setId($row->getId())
							->setIdentity($account)
							->setSecurity(intval($this->getRequest()->getPost('secure')));
					if($this->_post('remember')) {
						$secure->setExpirationSeconds(system_session::getOptions('remember_me_seconds'));
					}
					
					$row->setSecure($secure->getSecurity());
					$row->setLastupip($this->getRequest()->getClientIp());
					$row->setLastupdate(system_date::timestamp());
					$row->setLang($secure->getLanguage());
					$row->update();
					$this->_go();
				}
				$this->view->referer = $this->referer;
			} catch (Exception $e) {
				$this->view->exception = $e;
			}
		}
		$this->render();
	}
	
	public function action_logout() {
		system_user_instance::getInstance()->getSession()->logout();
		$this->_go();
	}
	
	public function action_error() {
		if(!$this->view->exception) {
			$this->view->exception = $this->getResponse()->getException();
		}
		$this->layout()->setLayout('layout');
		$this->render();
	}
	
	public function action_captcha() {
		system_image_captcha::getInstance($this->_namespace)->setCode()->display();
	}
}
